#include "StdAfx.h"
#include "Material.h"

VAMPIRE_NAMESPACE_BEGIN

Material::Material( const TString& name ) : mName(name), mpEffect(NULL)
{
	mpRenderQueue = new RenderQueue;
}

void Material::setRenderState()
{
	gpDevice->SetRenderState(D3DRS_SHADEMODE, mRPG.mShadeMode);
	gpDevice->SetRenderState(D3DRS_LIGHTING, mRPG.mLightEnable);
	gpDevice->SetRenderState(D3DRS_NORMALIZENORMALS, mRPG.mNormalizeNormals);
	gpDevice->SetRenderState(D3DRS_SPECULARENABLE, mRPG.mSpecularEnable);
	gpDevice->SetRenderState(D3DRS_FILLMODE, mRPG.mFillMode);
	gpDevice->SetRenderState(D3DRS_STENCILENABLE, mRPG.mStencilEnable);

	gpDevice->SetSamplerState(0, D3DSAMP_MAGFILTER, mRPG.mMagFilter);
	gpDevice->SetSamplerState(0, D3DSAMP_MINFILTER, mRPG.mMinFilter);
	if (D3DTEXF_ANISOTROPIC == mRPG.mMinFilter
		|| D3DTEXF_ANISOTROPIC == mRPG.mMagFilter)
	{
		gpDevice->SetSamplerState(0, D3DSAMP_MAXANISOTROPY, mRPG.mMaxAnisotropy);
	}

	gpDevice->SetSamplerState(0, D3DSAMP_MIPFILTER, D3DTEXF_LINEAR);
}

BOOL Material::initEffect()
{
	if(mRPG.mShaderFileName.empty())
	{
		return FALSE;
	}

	mpEffect = EffectManager::getSingletonPtr()->createEffect(mRPG.mShaderFileName, mRPG.mShaderClassName.c_str());

	return TRUE;
}

void Material::addRenderableToQueue( Renderable* obj )
{
	mpRenderQueue->addRenderable(obj);
}

void Material::removeRenderableFromQueue( Renderable* obj )
{
	mpRenderQueue->removeRenderable(obj);
}

RenderQueue* Material::getRenderQueue() const
{
	return mpRenderQueue;
}

UINT Material::preRender()
{
	return mpEffect->begin();
}

void Material::endRender()
{
	mpEffect->end();
}

void Material::beginPass( UINT id )
{
	mpEffect->beginPass(id);
}

void Material::endPass()
{
	mpEffect->endPass();
}

const RenderPriorityGroup& Material::getRPG() const
{
	return mRPG;
}

Effect* Material::getEffect() const
{
	return mpEffect;
}

VAMPIRE_NAMESPACE_END
